<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区 -->
    <el-card>
      <!-- 注意提示区 -->
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 完成步骤条 -->
      <el-steps style="margin:15px 0" :active="numberActive-0" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 切换标签页 -->
      <el-form :model="addruleForm" :rules="addrules" ref="addRuleForm" label-width="100px" label-position="top">
        <el-tabs v-model="numberActive" :tab-position="'left'" :before-leave="beforeTabLeave" @tab-click="switchBar">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addruleForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addruleForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addruleForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader :options="cateLists" :props="{ expandTrigger:'hover',value:'cat_id',label:'cat_name',children:'children'}" v-model="addruleForm.goods_cat" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的Item项动态属性 -->
            <el-form-item :label="item.attr_name" v-for="item in  manyParameter" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染表单的Item项静态属性 -->
            <el-form-item :label="item.attr_name" v-for="item in  onlyParameter" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload action="http://127.0.0.1:8888/api/private/v1/upload" :on-preview="handlePreview" :on-remove="handleRemove" list-type="picture" :headers="headerObj" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 文本编辑器 -->
            <quill-editor v-model="addruleForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addSp" class="btn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 浏览图片的对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" width="100%">
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  export default {
    name: 'GoodsAdd',
    data () {
      return {
        numberActive: '0',
        // 表单数据
        addruleForm: {
          goods_name: '',
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          // 商品分类列表
          goods_cat: [],
          // 上传的图片临时路径（对象）
          pics: [],
          // 商品详情介绍
          goods_introduce: '',
          attrs: []
        },
        // 存放图片的真实地址
        previewPath: '',
        previewVisible: false,

        // 商品列表数据
        cateLists: [],
        // 商品动态参数
        manyParameter: [],
        // 商品静态属性
        onlyParameter: [],
        // 表单验证规则
        // 图片Token表头
        headerObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        addrules: {
          goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
          goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
          goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
          goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        },
      }
    },
    created () {
      this.cateList()
    },
    methods: {
      // 获取商品列表
      async cateList () {
        const { data: res } = await this.$http.get('categories')
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品列表数据失败')
        }
        this.cateLists = res.data
        console.log(this.cateLists);
      },
      // 监听级联选择器变化事件
      handleChange () {
        console.log(this.addruleForm.goods_cat);
      },
      beforeTabLeave (activeName, oldActiveName) {
        if (oldActiveName === "0" && this.addruleForm.goods_cat.length !== 3) {
          this.$message.error('请选择商品分类')
          return false
        }
      },
      // 监听切换页切换事件
      async switchBar () {
        if (this.numberActive === '1') {
          // 获取动态参数
          const { data: res } = await
            this.$http.get(
              `categories/${this.addruleForm.goods_cat[2]}/attributes`, { params: { sel: 'many' } })
          if (res.meta.status !== 200) {
            return this.$message.error('获取商品动态参数失败')
          }
          console.log(res.data)
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
          });
          this.manyParameter = res.data
          console.log(this.manyParameter);
        } else if (this.numberActive === '2') {
          // 获取静态属性
          const { data: res } = await
            this.$http.get(
              `categories/${this.addruleForm.goods_cat[2]}/attributes`, { params: { sel: 'only' } })
          if (res.meta.status !== 200) {
            return this.$message.error('获取商品动态参数失败')
          }
          this.onlyParameter = res.data
        }
      },
      // 监听图片预览效果
      handlePreview (file) {
        this.previewPath = file.response.data.url
        this.previewVisible = true
      },
      // 监听文件列表移除图片时
      handleRemove (file) {
        // 1. 获取将要删除的图片的临时路径
        const filePath = file.response.data.tmp_path
        // 2. 从 addruleForm.pics 数组中，找到这个图片对应的索引值
        const i = this.addruleForm.pics.findIndex(item =>
          item.pic === filePath)
        // 3. 调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
        this.addruleForm.pics.splice(i, 1)
        console.log(this.addruleForm);
      },
      // 监听图片是否上传成功
      handleSuccess (response) {
        console.log(response);
        // 拼接得到一个图片信息对象
        const picInfo = { pic: response.data.tmp_path }
        // 将图片信息对象push到pics数组中
        this.addruleForm.pics.push(picInfo)
        console.log(this.addruleForm);
      },
      // 添加商品
      addSp () {
        // 全部表单预验证
        this.$refs.addRuleForm.validate(async valid => {
          if (!valid) {
            return
          }
          const form = _.cloneDeep(this.addruleForm)
          form.goods_cat = form.goods_cat.join(',')
          this.manyParameter.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_vals: item.attr_vals.join('')
            }
            this.addruleForm.attrs.push(newInfo)
          })
          this.onlyParameter.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_vals: item.attr_vals
            }
            this.addruleForm.attrs.push(newInfo)
          })
          form.attrs = this.addForm.attrs
          // 发起请求添加商品
          // 商品的名称，必须是唯一的
          const { data: res } = await this.$http.post('goods', form)

          if (res.meta.status !== 201) {
            return this.$message.error('添加商品失败！')
          }
          this.$message.success('添加商品成功！')
          this.$router.push('/goods')
        })
      }
    },
  }
</script>

<style lang="less" scoped>
.el-cascader{
  width: 240px;
}
.el-checkbox{
  margin: 0 10px 0 0 !important;
}

.btn{
  float:right;
  margin: 10px 0 0 0;
}
</style>